package com.migo.service.impl;

import com.migo.oss.OSSFactory;
import com.migo.service.ImageService;
import com.migo.utils.ImageBase64Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.util.UUID;

/**
 * Created by Wes on 2018/12/19.
 */
@Service("imageService")
public class ImageServiceImpl implements ImageService{


    @Autowired
    private OSSFactory ossFactory;


    @Override
    public String uploadOne(String imageBase64) {
        try {
            if (!StringUtils.isEmpty(imageBase64)) {
                String imageType = ImageBase64Utils.getImageType(String.valueOf(imageBase64));
                String imageStr = ImageBase64Utils.replacePre(String.valueOf(imageBase64));
                BASE64Decoder decoder = new BASE64Decoder();
                // Base64解码
                byte[] b = decoder.decodeBuffer(imageStr);
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {// 调整异常数据
                        b[i] += 256;
                    }
                }
                // 生成jpeg图片
                String imgFilePath = UUID.randomUUID().toString() + "." + imageType;// 新生成的图片
                return ossFactory.build().upload(imgFilePath, b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
